package com.qinggeng.project.system.controller;

import java.util.ArrayList;
import java.util.List;

import com.qinggeng.common.enums.ShowTypeEnum;
import com.qinggeng.common.enums.UserTypeEnum;
import com.qinggeng.common.utils.SecurityUtils;
import com.qinggeng.framework.web.domain.server.Sys;
import com.qinggeng.project.api.service.IApiMemberService;
import com.qinggeng.project.system.domain.SysUser;
import com.qinggeng.project.system.service.ISysUserService;
import com.qinggeng.project.tool.sms.service.ISysSmsService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qinggeng.framework.aspectj.lang.annotation.Log;
import com.qinggeng.framework.aspectj.lang.enums.BusinessType;
import com.qinggeng.project.system.domain.DistributionPoint;
import com.qinggeng.project.system.service.IDistributionPointService;
import com.qinggeng.framework.web.controller.BaseController;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.common.utils.poi.ExcelUtil;
import com.qinggeng.framework.web.page.TableDataInfo;

/**
 * 配送点Controller
 *
 * @author qinggeng
 * @date 2020-06-16
 */
@RestController
@RequestMapping("/system/point")
public class DistributionPointController extends BaseController {

    @Autowired
    private IDistributionPointService distributionPointService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IApiMemberService memberService;

    @Autowired
    private ISysSmsService smsService;

    /**
     * 查询配送点列表
     */
    @PreAuthorize("@ss.hasPermi('system:point:list')")
    @GetMapping("/list")
    public TableDataInfo list(DistributionPoint distributionPoint) {
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            distributionPoint.setShopId(SecurityUtils.getShopId());
        }
        distributionPoint.setDelFalg("10");
        startPage();
        List<DistributionPoint> list = distributionPointService.selectDistributionHandleList(distributionPoint);

        return getDataTable(list);
    }

    /**
     * 获取未绑定骑手的配送点列表
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:point:list')")
    @GetMapping("/pointList")
    public TableDataInfo pointListWithoutCourier(){
        DistributionPoint where=new DistributionPoint();
        //如果用户类型为商户
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            where.setShopId(SecurityUtils.getShopId());
        }
        where.setDelFalg("10");
        List<DistributionPoint> pointList=new ArrayList<>();
        for (DistributionPoint point:distributionPointService.selectDistributionPointList(where)
        ) {
            if(point.getCourierId()==null){//courierId为空
                pointList.add(point);
            }
        }
        return getDataTable(pointList);
    }

    /**
     * 获取未绑定配送点的骑手列表
     */
    @PreAuthorize("@ss.hasPermi('system:point:list')")
    @GetMapping("/riderList")
    public List<SysUser> riderList() {
        SysUser where=new SysUser();
        where.setUserType(UserTypeEnum.COURIER.getCode());
        List<SysUser> list =new ArrayList<>() ;
        for (SysUser user : userService.selectUserList(where)) {
            if(distributionPointService.selectPointByCourierId(user.getUserId())==null){
                list.add(user);
            }
        }
        return list;
    }

    /**
     * 导出配送点列表
     */
    @PreAuthorize("@ss.hasPermi('system:point:export')")
    @Log(title = "配送点", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(DistributionPoint distributionPoint) {
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            distributionPoint.setShopId(SecurityUtils.getShopId());
        }
        List<DistributionPoint> list = distributionPointService.selectDistributionPointList(distributionPoint);
        ExcelUtil<DistributionPoint> util = new ExcelUtil<DistributionPoint>(DistributionPoint.class);
        return util.exportExcel(list, "point");
    }

    /**
     * 获取配送点详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:point:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(distributionPointService.selectDistributionPointById(id));
    }

    /**
     * 新增配送点
     */
    @PreAuthorize("@ss.hasPermi('system:point:add')")
    @Log(title = "配送点", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DistributionPoint point) {
        SysUser courier=memberService.selectByPhone(point.getPointPhone(),UserTypeEnum.COURIER.getCode());
        if(courier==null){
            String password=point.getPointPhone().substring(3,9);
            courier=memberService.insertPhone(point.getPointPhone(),password,point.getPointName(),UserTypeEnum.COURIER.getCode());
        }
        DistributionPoint oldPoint=distributionPointService.selectPointByCourierId(courier.getUserId());
        if(oldPoint==null){
            point.setCourierId(courier.getUserId());
            return toAjax(distributionPointService.insertDistributionPoint(point));
        }else{
            return AjaxResult.error("手机号码已被绑定！",ShowTypeEnum.用户.getValue());
        }
    }

    /**
     * 修改配送点
     */
    @PreAuthorize("@ss.hasPermi('system:point:edit')")
    @Log(title = "配送点", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DistributionPoint point ) {
        String oldPhone=distributionPointService.selectDistributionPointById(point.getId()).getPointPhone();
        if(!oldPhone.equals(point.getPointPhone())){
            SysUser courier=memberService.selectByPhone(point.getPointPhone(),UserTypeEnum.COURIER.getCode());
            if(courier==null){
                String password=point.getPointPhone().substring(3,9);
                courier=memberService.insertPhone(point.getPointPhone(),password,point.getPointName(),UserTypeEnum.COURIER.getCode());
            }
            point.setCourierId(courier.getUserId());
        }
        return toAjax(distributionPointService.updateDistributionPoint(point));
    }

    /**
     * 删除配送点
     */
    @PreAuthorize("@ss.hasPermi('system:point:remove')")
    @Log(title = "配送点", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(distributionPointService.deleteDistributionPointByIds(ids));
    }

    @PostMapping("/addCourier")
    public AjaxResult addCourier(Long pointId, SysUser user){
        AjaxResult result=new SysUserController().add(user);
        if((Integer)result.get(AjaxResult.DATA_TAG)>0){
            return toAjax(distributionPointService.updatePointSetCourierId(pointId,user.getUserId()));
        }
        return toAjax(0);
    }

    @PostMapping("/deleteCourier")
    public AjaxResult deleteCourier(Long pointId){
        return toAjax(distributionPointService.updatePointSetCourierId(pointId,null));
    }

    @PostMapping("/updateCourier")
    public AjaxResult updateCourier(Long pointId,Long courierId){
        return toAjax(distributionPointService.updatePointSetCourierId(pointId,courierId));
    }
}
